package com.UdpRecieve.framework.interceptor;


import com.UdpRecieve.tool.Global;
import com.UdpRecieve.tool.StringUtils;
import com.UdpRecieve.framework.constant.ServletConstant;
import com.UdpRecieve.tool.CookieUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);



    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler)throws Exception {

        String token = CookieUtils.getCookieValue(request, ServletConstant.WEB_TOKEN);
        String sessionKey = ServletConstant.SESSION_KEY + token;
        String userName = (String) request.getSession().getAttribute(sessionKey);
        logger.info("Cookie:"+token);
        logger.info("session:"+userName);
        logger.info("当前线程号:"+Thread.currentThread().getId());
        if (!StringUtils.isEmpty(userName)) {//有session
            return true;
        } else if (!StringUtils.isEmpty(token) && StringUtils.isEmpty(userName)) {//token有单session没有,登录超时
            request.setAttribute("msg","登录已经超时");
            CookieUtils.deleteCookie(request, response,ServletConstant.WEB_TOKEN);
            request.getRequestDispatcher("login").forward(request, response);
            return false;
        } else{//两个都为空,第一次登录

            //清除在线用户
            System.out.println("sessionId:"+request.getSession().getId());
            ServletConstant.OnlineUserList.entrySet().removeIf(entry -> entry.getKey() != request.getSession().getId());

            //请求转发到登录界面
            //System.out.println(request.getRequestURI());
            response.sendRedirect(Global.getContentPath()+"login");
            return false;
        }

    }
}
